# -*- coding: utf-8 -*-
import hashlib
import json
import random
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_QUERY_GATEWAY = 'http://www.szsflwkj.com/pay/payquery'

APP_CONF = {
    '1157': {
        'API_KEY': 'FBC4C8C5735C4C4F869D3A576E9AFA98',
        'gateway': 'http://www.szsflwkj.com/pay/payment',
    },
    '1159': {
        'API_KEY': '5BF7A2F2D8D049DCAB7AC314D7F80E4D',
        'gateway': 'http://www.szsflwkj.com/pay/payment',
    },
    '1170': {
        'API_KEY': 'FC5FBBD91D5C430FA9336951D82F71A6',
        'gateway': 'http://www.szsflwkj.com/pay/payment',
    },
    '1063': {  # 测试账户 994ff9237c244e5cbdf37794d68e349f
        # 'API_KEY': 'F0272785323941798A41B201786BBBDE',
        'API_KEY': '994ff9237c244e5cbdf37794d68e349f',
        'gateway': 'http://www.szsflwkj.com/pay/payment',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=' + key
    _LOGGER.info("e_times sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("e_times sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 支付宝Wap HFAliPayH5
#    微信wap：YYKWXWAP HFWXH5WGW HFWXH5
# 微信扫码：HFWXPay
#    QQ扫码：HFQQPay
#    QQ Wap:YHXFQQWAP
# 银联 GFBWY

# wxpay1 1170 dwc专用
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'HFWXH5'
    elif service == 'wxpay1':
        # payType = 'HFWXH5WGW'
        payType = 'YYKWXWAP'
    elif service == 'alipay':
        payType = 'HFAliPayH5'
    elif service == 'alipay1':
        payType = 'YHXFALIWAP'
    elif service == 'qq':
        payType = 'HFQQWAP'
    elif service == 'bank':
        payType = 'HFYLWAP'
    else:
        payType = 'HFYLWAP'
    return payType


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if pay_amount >= 10 and int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    # pay_amount = _fix_pay_amount(pay, pay_amount)
    parameter_dict = OrderedDict((
        ('service', _get_pay_type(service)),
        ('version', 'v1.0'),
        ('signtype', 'MD5'),
        ('merchantid', app_id),
        ('shoporderId', str(pay.id)),
        ('totalamount', str(pay_amount)),
        ('productname', 'charge'),
        ('notify_url', '{}/pay/api/{}/e_times/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('callback_url', '{}/pay/api/{}/e_times/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('nonce_str', '213123123123'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("e_times create: %s", parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info("e_times create rsp: %s, %s", response.text, response.url)
    data = json.loads(response.text)
    return {'charge_info': data['code_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("e_times notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['shoporderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('e_times event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['result_code'])
    trade_no = data['orderid']
    total_fee = float(data['total_fee'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':
        _LOGGER.info('e_times check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantid', app_id),
        ('shoporderid', str(pay_order.id)),
        ('orderdate', time.strftime("%Y-%m-%d", time.localtime())),
        ('nonce_str', '213123123123'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('e_times query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info('e_times query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['state']
        total_fee = float(data['total_fee'])
        trade_no = data['orderid']
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '1' and total_fee > 0:
            _LOGGER.info('e_times query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
